package com.ruoyi.classai.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.classai.domain.EwcResource;
import com.ruoyi.classai.domain.EwcResourceDetails;
import com.ruoyi.classai.domain.dto.resource.EwcResourceAddDto;
import com.ruoyi.classai.domain.dto.resource.EwcResourceQueryDto;
import com.ruoyi.classai.mapper.EwcResourceMapper;
import com.ruoyi.classai.service.IEwcResourceDetailsService;
import com.ruoyi.classai.service.IEwcResourceService;
import com.ruoyi.classai.utils.FileUtil;
import com.ruoyi.common.core.exception.GlobalException;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.bean.BeanUtils;
import com.ruoyi.common.security.utils.SecurityUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 资源库Service业务层处理
 *
 * @date 2025-03-17
 */
@Service
public class EwcResourceServiceImpl extends ServiceImpl<EwcResourceMapper, EwcResource> implements IEwcResourceService {


    @Autowired
    private IEwcResourceDetailsService ewcResourceDetailsService;

    /**
     * 查询资源库列表
     *
     * @param dto 资源库信息
     * @return 资源库集合
     */
    @Override
    public List<EwcResource> selectResourceList(EwcResourceQueryDto dto) {
        LambdaQueryWrapper<EwcResource> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(dto.getResourceName()), EwcResource::getResourceName, dto.getResourceName())
                .eq(dto.getGradeType() != null, EwcResource::getGradeType, dto.getGradeType())
                .eq(dto.getSubjectType() != null, EwcResource::getSubjectType, dto.getSubjectType())
                .eq(EwcResource::getStatus, 1)
                .orderByDesc(EwcResource::getCreateTime);
        return this.list(queryWrapper);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void insertResource(EwcResourceAddDto addDto) {
        // 参数校验
        if (StringUtils.isEmpty(addDto.getResourceName())) {
            throw new GlobalException("资源名称不能为空");
        }
        // 检查资源名称是否已存在
        LambdaQueryWrapper<EwcResource> queryWrapper = Wrappers.lambdaQuery(EwcResource.class)
                .eq(EwcResource::getResourceName, addDto.getResourceName());
        if (this.count(queryWrapper) > 0) {
            throw new GlobalException("资源名称已存在");
        }
        // 设置默认值
        if (addDto.getBrowseNum() == null) {
            addDto.setBrowseNum(0);
        }
        // 当前时间
        Date nowDate = DateUtils.getNowDate();

        EwcResource resource = new EwcResource();
        BeanUtils.copyProperties(addDto, resource, "id");
        // 设置创建者和创建时间
        resource.setCreator(SecurityUtils.getUsername());
        resource.setCreatorId(String.valueOf(SecurityUtils.getUserId()));
        resource.setCreateTime(nowDate);
        resource.setStatus(1);
        this.save(resource);
        if (CollectionUtils.isNotEmpty(addDto.getResourceFiles())) {
            List<EwcResourceDetails> collect = addDto.getResourceFiles().stream().map(r -> {
                EwcResourceDetails resourceDetails = new EwcResourceDetails();
                BeanUtils.copyProperties(r, resourceDetails);
                resourceDetails.setResourceId(resource.getId());
                resourceDetails.setCreateTime(nowDate);
                String resourceSuffix = FileUtil.getResourceSuffix(r.getResourceUrl());
                resourceDetails.setFileDetails(resourceSuffix);
                resourceDetails.setFileType(FileUtil.getFileType(resourceSuffix));
                return resourceDetails;
            }).collect(Collectors.toList());
            ewcResourceDetailsService.saveBatch(collect);
        }
    }

    @Override
    public EwcResource getResourceById(String id) {
        EwcResource ewcResource = this.getById(id);
        if (Objects.isNull(ewcResource) || ewcResource.getStatus() == 0) {
            throw new GlobalException("资源不存在");
        }
        List<EwcResourceDetails> list = ewcResourceDetailsService.list(new LambdaQueryWrapper<EwcResourceDetails>().eq(EwcResourceDetails::getResourceId, id));
        if (CollectionUtils.isNotEmpty(list)) {
            ewcResource.setResourceDetails(list);
        }
        return ewcResource;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateResource(EwcResourceAddDto dto) {
        if (StringUtils.isEmpty(dto.getId())) {
            throw new GlobalException("ID不存在");
        }
        EwcResource oldResource = this.getById(dto.getId());
        if (Objects.isNull(oldResource) || oldResource.getStatus() == 0) {
            throw new GlobalException("资源不存在");
        }
        String newResourceName = dto.getResourceName();
        String oldResourceName = oldResource.getResourceName();
        if (!newResourceName.equals(oldResourceName)) {
            LambdaQueryWrapper<EwcResource> queryWrapper = new LambdaQueryWrapper<EwcResource>()
                    .eq(EwcResource::getResourceName, newResourceName)
                    .ne(EwcResource::getId, dto.getId());
            if (this.count(queryWrapper) > 0) {
                throw new GlobalException("资源名称已存在");
            }
        }
        BeanUtils.copyProperties(dto, oldResource);
        Date nowDate = DateUtils.getNowDate();
        oldResource.setUpdateTime(nowDate);
        this.updateById(oldResource);
        ewcResourceDetailsService.remove(new LambdaQueryWrapper<EwcResourceDetails>().eq(EwcResourceDetails::getResourceId, dto.getId()));
        if (CollectionUtils.isNotEmpty(dto.getResourceFiles())) {
            List<EwcResourceDetails> collect = dto.getResourceFiles().stream().map(r -> {
                EwcResourceDetails resourceDetails = new EwcResourceDetails();
                BeanUtils.copyProperties(r, resourceDetails);
                resourceDetails.setResourceId(dto.getId());
                resourceDetails.setCreateTime(nowDate);
                String resourceSuffix = FileUtil.getResourceSuffix(r.getResourceUrl());
                resourceDetails.setFileDetails(resourceSuffix);
                resourceDetails.setFileType(FileUtil.getFileType(resourceSuffix));
                return resourceDetails;
            }).collect(Collectors.toList());
            ewcResourceDetailsService.saveBatch(collect);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteResourceByIds(List<String> ids) {
        List<EwcResource> list = this.list(new LambdaQueryWrapper<EwcResource>().in(CollectionUtils.isNotEmpty(ids), EwcResource::getId, ids));
        List<String> resourceIds = list.stream().map(EwcResource::getId).collect(Collectors.toList());
        ewcResourceDetailsService.remove(new LambdaQueryWrapper<EwcResourceDetails>().in(EwcResourceDetails::getResourceId, resourceIds));
        this.removeByIds(resourceIds);
    }

}
